//
//  GlobalTableViewCell.swift
//  ZYA
//
//  Created by 邱仙凯 on 2021/8/6.
//  Copyright © 2021 aowang. All rights reserved.
//

import UIKit

let NewStatusColorDic = ["未提交":UIColor(kshex: "#8991B0"),
                            "未审核":UIColor(kshex: "#8991B0"),
                            "已提交":UIColor(kshex:"#6DBB75"),
                         "审核中":UIColor(kshex:"#6DBB75"),

                            "已审核":UIColor(kshex:"#4972F9"),
                            "已退回":UIColor(kshex: "#D65D50"),
                         "退回":UIColor(kshex: "#D65D50"),

                            "已回退":UIColor(kshex: "#D65D50"),
                            "新增":UIColor(kshex: "#D65D50"),
                            "建档":UIColor(kshex:"#6DBB75"),
                            "拜访中":UIColor(kshex: "#D65D50"),
                            "已拜访":UIColor(kshex:"#6DBB75"),
                         "已评定":UIColor(kshex:"#4972F9"),

                         "":UIColor.clear]


let NewGridentTopBgDic = ["未提交":UIColor(kshex: "#E2E6F1"),
                            "未审核":UIColor(kshex: "#E2E6F1"),
                            "已提交":UIColor(kshex:"#E6FFE7"),
                          "审核中":UIColor(kshex:"#E6FFE7"),

                            "已审核":UIColor(kshex:"#CEE0FF"),
                            "已退回":UIColor(kshex: "#FFEAE6"),
                          "退回":UIColor(kshex: "#FFEAE6"),

                            "已回退":UIColor(kshex: "#FFEAE6"),
                            "新增":UIColor(kshex: "#FFEAE6"),
                            "建档":UIColor(kshex:"#E6FFE7"),
                            "拜访中":UIColor(kshex: "#FFEAE6"),
                            "已拜访":UIColor(kshex:"#E6FFE7"),
                          "已评定":UIColor(kshex:"#CEE0FF"),

                            "":UIColor(kshex:"#E2E6F1")]
let NewGridentBottomBgDic = ["未提交":UIColor(kshex: "#f3f4f7"),
                            "未审核":UIColor(kshex: "#f3f4f7"),
                            "已提交":UIColor(kshex:"#f5fef5"),
                             "审核中":UIColor(kshex:"#f5fef5"),

                            "已审核":UIColor(kshex:"#f0f6ff"),
                            "已退回":UIColor(kshex: "#FFf9f8"),
                             "退回":UIColor(kshex: "#FFf9f8"),

                            "已回退":UIColor(kshex: "#FFf9f8"),
                            "新增":UIColor(kshex: "#FFf9f8"),
                            "建档":UIColor(kshex:"#f5fef5"),
                            "拜访中":UIColor(kshex: "#FFf9f8"),
                            "已拜访":UIColor(kshex:"#f5fef5"),
                             "已评定":UIColor(kshex:"#f0f6ff"),

                            "":UIColor(kshex:"#f3f4f7")]

 
class GlobalTableViewCell: UITableViewCell {
    
    var defaultLeftColor = UIColor(kshex: "#8991B0")
    var defaultRightColor =  UIColor(kshex: "#222222")
    
    lazy  var bg:GradientView = {
        let v = GradientView()
        v.backgroundColor = .white
        v.layer.cornerRadius = 8
        v.layer.masksToBounds = true
        return v
    }()
    lazy  var topV:GradientView = {
        let v = GradientView()
        v.backgroundColor = .clear
         return v
    }()
  
    lazy  var operateV:UIView = {
        let v = UIView()
        v.backgroundColor = .clear
         return v
    }()
    lazy var operateBtn:OperateBtnGroup = {
        let v = OperateBtnGroup(frame: CGRect.zero,btnAlignment:.right,cRadius_group: 14, titles: [],bWidth_group: 80)
        return v
    }()
 
    lazy var leftBottomImg:UIImageView = {
        let v = UIImageView()
        return v
    }()
    private var itemLeading:CGFloat = 10 {
        didSet {
            if oldValue != itemLeading {
                self.contLabArr[0].0.snp.updateConstraints { make in
                    make.left.equalTo(bg).offset(itemLeading)
                }
            }
        }
    }
    // 项目名称的长度，有特殊需求可以覆盖修改
  private var itemW:CGFloat = 0 {
        didSet {
            if oldValue != itemW { 
                for i in 0..<self.contLabArr.count {
                    self.contLabArr[i].0.snp.updateConstraints { make in
                        make.width.equalTo(itemW)
                    }
                }
            }
        }
    }
 
    // 可以选择
    var cellSelectable = false {
        didSet {
            if oldValue != cellSelectable {
                if cellSelectable {
                    if selBtn.superview.isNone {
                        bg.addSubview(selBtn)
                        selBtn.snp.makeConstraints { make in
                            make.width.height.equalTo(22)
                            make.left.equalTo(bg).offset(10)
                            make.top.equalTo(bg).offset(7)
                        }
                        self.itemLeading = 42
                        
                        if titleLab.superview != nil {
                            self.titleLab.snp.updateConstraints { make in
                                make.left.equalToSuperview().offset(self.itemLeading)
                            }
                        }
                    }
                } else {
                    selBtn.removeFromSuperview()
                    self.itemLeading = 10
                    
                    if titleLab.superview != nil {
                        self.titleLab.snp.updateConstraints { make in
                            make.left.equalToSuperview().offset(self.itemLeading)
                        }
                    }
                }
            }
        }
    }
    
    func setSelect(_ flag:Bool) {
        selBtn.isSelected = flag
    }
    
    lazy var selBtn: UIButton = {
        let v = UIButton()
        v.isUserInteractionEnabled = false
        v.setBackgroundImage(UIImage(named:"selectButton"), for: .normal)
        v.setBackgroundImage(UIImage(named:"selectedButton"), for: .selected)
        return v
    }()
    
    
    private var contLabArr = [(UILabel,UILabel)]()
    /// 设置内容
    func setDataSource(contentArr:[(String,String?)]!,btnTitleArr:[String]? = nil,imgStrArr:[String]? = nil,titleAndStatus:(String,String)? = nil, isSelected: Bool = false) {
        let colorContentArr = contentArr.compactMap{ ($0.0,$0.1,"") }
        self.setDataSource(contentArr: colorContentArr,btnTitleArr: btnTitleArr,imgStrArr: imgStrArr,titleAndStatus: titleAndStatus, isSelected: isSelected)
    }
    /// 设置内容  contentArr（左标题，右内容，颜色）
    func setDataSource(contentArr:[(String,String?,String)]!,btnTitleArr:[String]? = nil,imgStrArr:[String]? = nil,titleAndStatus:(String,String)? = nil, isSelected: Bool = false) {
        
        // 标题和状态
        if let titleAndStatus = titleAndStatus {
            topV.snp.remakeConstraints { make in
                make.height.equalTo(38)
               make.left.right.top.equalTo(bg)
            }
            self.addTitleLab()
            self.addStatusLab()
            self.titleLab.text = titleAndStatus.0
            self.statusBtn.setTitle(titleAndStatus.1, for: .normal)
            if let dColor = NewStatusColorDic[titleAndStatus.1] {
                self.statusBtn.backgroundColor = dColor
                self.statusBtn.setTitleColor(.white, for: .normal)

            } else {
                let walpha = UIColor(white: 1, alpha: 0.3)
                self.statusBtn.backgroundColor = walpha
                self.statusBtn.setTitleColor(.darkGray, for: .normal)
            }
            
            
            let grColor = NewGridentTopBgDic[titleAndStatus.1] ?? UIColor(kshex:"#CEE0FF")
            self.topV.setGradient(type: .left2right, startColor: grColor, endColor: .white)
            
            let grbbColor = NewGridentBottomBgDic[titleAndStatus.1] ?? UIColor(kshex:"#f0f6ff")
            self.bg.setGradient(type: .left2right, startColor: grbbColor, endColor: .white)
         }
        
        var bottomH:CGFloat = 0
    
        // 文字按钮群
        if let btnTitleArr = btnTitleArr, btnTitleArr.count > 0 {
             self.addBtnGroup()
            var title_colorss = [UIColor]()
            var border_colorss = [UIColor]()
            var bg_colorss = [UIColor]()

 

            for i in 0..<btnTitleArr.count {
                if btnTitleArr[i] == "提交" {
                    title_colorss.append(UIColor(kshex: "#2A304A"))
                    border_colorss.append(UIColor(kshex: "#cacee1"))
                    bg_colorss.append(UIColor(kshex: "#ECEEF3"))
                } else {
                     
                    title_colorss.append(UIColor(kshex: "#8991B0"))
                    border_colorss.append(UIColor(kshex: "#cacee1"))
                    bg_colorss.append(.clear)
                }
            }
            
            operateBtn.set4SpecialBorder(btnTitleArr, titltColors: title_colorss, borderColors: border_colorss, bgColors: bg_colorss)
            
//              operateBtn.setTitle(btnTitleArr,colors:colorss)
            bottomH += 34
        } else if let imgStrArr = imgStrArr, imgStrArr.count > 0  {
            // 图片按钮群, 会覆盖了文字按钮群
            self.addBtnGroup()
            operateBtn.setTitle([])
             operateBtn.setImgs(imgStrArr, bWidth_group: 30)
            bottomH += 34
        } else {
            // 没有的时候要赋值为空，防止复用出错
            operateBtn.setTitle([])
         }
        if bottomH > 68 {
            bottomH = 68
        }
        operateV.snp.remakeConstraints { make in
            make.height.equalTo(bottomH)
           make.left.right.bottom.equalTo(bg)
        }
        var tempW:CGFloat = 0
        // 内容赋值
        for i in 0..<contLabArr.count {
            let leftLab = contLabArr[i].0
            let rightLab = contLabArr[i].1
            var dfLeftcolors = defaultLeftColor
            var dfRightcolors = defaultRightColor

            if i < contentArr.count && contentArr[i].2.count > 0 {
                dfLeftcolors = UIColor(kshex:contentArr[i].2)
                dfRightcolors = UIColor(kshex:contentArr[i].2)

            }
            leftLab.textColor = dfLeftcolors
            rightLab.textColor = dfRightcolors
            if i < contentArr.count {
  
                leftLab.text = contentArr[i].0
            // 算宽，左边的宽
                let new_W:CGFloat = CGFloat(contentArr[i].0.count * 18)
                 tempW = tempW < new_W ? new_W : tempW

            
                let conS = contentArr[i].1.unwrap.isEmpty ? "-" : contentArr[i].1
                rightLab.text = conS
            } else {
                leftLab.text = ""
                rightLab.text = ""
            }
        }
        // 算宽，左边的宽  不能超过一半
        if tempW > KSGlobal.screenW/2 - 20 {
            tempW = KSGlobal.screenW/2 - 20
        }
        // 自动判断前置宽度
        self.itemW = tempW
        
        if cellSelectable {
            setSelect(isSelected)
        }
  
        makeConstX(contentCount: contentArr.count)
       
    }
    
    var btnGroupclickAction:((Int,String)->())? {
        didSet {
            self.operateBtn.clickAction = btnGroupclickAction!
 
        }
    }
   
    
    // 原来的布局  内容行数
    var contentCount:Int?
    
 
 
    func makeConstX(contentCount:Int) {
        // 有变化了再去重新设置
        if self.contentCount != contentCount {
            
            for i in 0..<contLabArr.count {
                let labL = contLabArr[i].0
                let labR = contLabArr[i].1
                
                labL.snp.remakeConstraints { make in
                    if i == 0 {
                        make.left.equalTo(bg).offset(itemLeading)
                    } else {
                        make.left.equalTo(contLabArr[i - 1].0)
                    }
                    make.width.equalTo(itemW)
                    make.top.equalTo(labR)
                }
                labR.snp.remakeConstraints { make in
                    make.left.equalTo(labL.snp.right).offset(6)
                    make.right.equalTo(bg).offset(-5)
                    if i == 0 {
                          make.top.equalTo(topV.snp.bottom).offset(8)
                     } else {
                        make.top.equalTo(contLabArr[i - 1].1.snp.bottom).offset(8)
                    }
                    if i == (contentCount - 1) {
                        make.bottom.equalTo(operateV.snp.top).offset(-8)
                    }
                }
            }
            
              self.contentCount = contentCount
        }
        
        
        
    }
    // 给某行设置颜色
    func setSomeLineColor(line:Int,color:UIColor) {
        let itemLab = contLabArr[line].0
        let contLab = contLabArr[line].1
             itemLab.textColor = color
            contLab.textColor = color
     }
    // 给某行设置颜色
    func setSomeLineBgColor(line:Int,color:UIColor) {
        let itemLab = contLabArr[line].0
        let contLab = contLabArr[line].1
        itemLab.backgroundColor = color
        contLab.backgroundColor = color
     }
    
    private func addTitleLab() {
        if titleLab.superview.isNone {
            topV.addSubview(titleLab)
            titleLab.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(10)
                make.right.equalToSuperview().offset(-3)
                make.centerY.equalTo(topV)
            }
        }
    }
    private func addStatusLab() {
        if statusBtn.superview.isNone {
            topV.addSubview(statusBtn)
            statusBtn.snp.makeConstraints { make in
                make.right.equalTo(topV).offset(-8)
                make.centerY.equalTo(topV)
                make.width.equalTo(54)
                make.height.equalTo(24)
            }
        }
    }
 //  把删除按钮转为图片 放左边
    private func addBtnGroup() {
        if operateBtn.superview.isNone {
            operateV.addSubview(operateBtn)
            operateBtn.snp.makeConstraints { make in
                make.left.equalTo(operateV).offset(10)
                make.right.equalTo(operateV).offset(-10)
                make.bottom.equalTo(operateV).offset(-4)
                make.height.equalTo(28)
            }
        }
    }
    lazy private var titleLab:UILabel = {
        let v = UILabel()
        v.font = UIFont.boldSystemFont(ofSize: 16)
        return v
    }()
    lazy private var statusBtn:UIButton = {
        let v = UIButton()
        v.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
        v.setTitleColor(.white, for: .normal)
        v.layer.cornerRadius = 5
        return v
    }()
   
    
    func setTitleFont(_ font:UIFont) {
        titleLab.font = font
    }
 
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        self.backgroundColor = Theme.awModuleBgColor
        self.contentView.backgroundColor = Theme.awModuleBgColor
        self.contentView.addSubview(bg)
        bg.snp.makeConstraints { make in
            make.left.equalTo(self.contentView).offset(6)
            make.top.equalTo(self.contentView).offset(6)
            make.right.equalTo(self.contentView).offset(-6)
            make.bottom.equalTo(self.contentView)
        }
        bg.addSubview(topV)
        topV.snp.makeConstraints({ make in
             make.height.equalTo(1)
            make.left.right.top.equalTo(bg)
        })
 
        bg.addSubview(operateV)
        operateV.snp.makeConstraints({ make in
             make.height.equalTo(1)
            make.left.right.bottom.equalTo(bg)
        })
  
        
        bg.addSubview(leftBottomImg)
        leftBottomImg.snp.makeConstraints { (make) in
            make.left.equalTo(bg).offset(10)
            make.height.equalTo(22)
            make.width.equalTo(20)
            make.top.equalTo(bg).offset(27)
        }
        
        for _ in 0..<30 {
            let labL = UILabel()
            labL.textColor = defaultLeftColor
            labL.font = UIFont.boldSystemFont(ofSize: 14)
            bg.addSubview(labL)
            
            let labR = UILabel()
            labR.textColor = defaultRightColor
            labR.font = UIFont.boldSystemFont(ofSize: 14)
            labR.numberOfLines = 0
            bg.addSubview(labR)
            contLabArr.append((labL,labR))
            
        }
    }
    
    
    
    
    
    var titleTabClosure:(()->())?
    // 让第一个标签支持点击事件
    func  setTitleTouchable() {
        titleLab.isUserInteractionEnabled = true
        titleLab.font = UIFont.systemFont(ofSize: 17)
        titleLab.textColor = .blue
        titleLab.underline()
        let singleTap = UITapGestureRecognizer(target: self, action:
                                                #selector(tabGesture))
        titleLab.addGestureRecognizer(singleTap)
    }
    @objc func tabGesture() {
        if let clo = titleTabClosure {
            clo()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
}
